<template>
  <div class="bg-white dark:bg-[#141414] rounded-lg shadow-lg p-6">
    <div class="flex items-center justify-between mb-6">
      <h2 class="text-xl font-bold text-gray-900 dark:text-white flex items-center">
        <Activity class="w-5 h-5 mr-2 text-blue-500" />
        {{ t('components.realtime_monitor.title') }}
      </h2>
      <div class="flex items-center space-x-2">
        <div :class="[
          'w-3 h-3 rounded-full animate-pulse',
          isRunning ? 'bg-green-500' : 'bg-gray-400'
        ]"></div>
        <span class="text-sm text-gray-600 dark:text-gray-400">
          {{ isRunning ? t('components.realtime_monitor.monitoring') : t('components.realtime_monitor.not_running') }}
        </span>
      </div>
    </div>

    <div v-if="!isRunning" class="text-center py-8 text-gray-500 dark:text-gray-400">
      <Monitor class="w-12 h-12 mx-auto mb-3 opacity-50" />
      <p>{{ t('components.realtime_monitor.not_running_hint') }}</p>
    </div>

    <div v-else class="space-y-6">
      <!-- 实时数据卡片 -->
      <div class="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <div class="bg-gradient-to-r from-blue-500 to-blue-600 rounded-lg p-4 text-white">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-blue-100 text-sm font-medium">{{ t('components.realtime_monitor.real_time_speed') }}</p>
              <p class="text-2xl font-bold">{{ formattedCurrentSpeed }}</p>
              <p class="text-blue-100 text-xs">{{ formattedSpeedMBps }}</p>
            </div>
            <Zap class="w-8 h-8 text-blue-200" />
          </div>
        </div>

        <div class="bg-gradient-to-r from-green-500 to-green-600 rounded-lg p-4 text-white">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-green-100 text-sm font-medium">{{ t('components.realtime_monitor.peak_speed') }}</p>
              <p class="text-2xl font-bold">{{ formattedPeakSpeed }}</p>
              <p class="text-green-100 text-xs">{{ t('components.realtime_monitor.highest_record') }}</p>
            </div>
            <TrendingUp class="w-8 h-8 text-green-200" />
          </div>
        </div>

        <div class="bg-gradient-to-r from-orange-500 to-orange-600 rounded-lg p-4 text-white">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-orange-100 text-sm font-medium">{{ t('components.realtime_monitor.avg_speed') }}</p>
              <p class="text-2xl font-bold">{{ formattedAvgSpeed }}</p>
              <p class="text-orange-100 text-xs">{{ t('components.realtime_monitor.during_runtime') }}</p>
            </div>
            <BarChart3 class="w-8 h-8 text-orange-200" />
          </div>
        </div>

        <div class="bg-gradient-to-r from-purple-500 to-purple-600 rounded-lg p-4 text-white">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-purple-100 text-sm font-medium">{{ t('components.realtime_monitor.active_connections') }}</p>
              <p class="text-2xl font-bold">{{ activeConnections }}</p>
              <p class="text-purple-100 text-xs">{{ t('components.realtime_monitor.concurrent_tasks') }}</p>
            </div>
            <Wifi class="w-8 h-8 text-purple-200" />
          </div>
        </div>
      </div>

      <!-- 实时图表 -->
      <div class="bg-gray-50 dark:bg-[#141414] rounded-lg p-4">
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
            {{ t('components.realtime_monitor.speed_trend') }}
          </h3>
          <div class="flex items-center space-x-4 text-sm">
            <div class="flex items-center">
              <div class="w-3 h-3 bg-blue-500 rounded-full mr-2"></div>
              <span class="text-gray-600 dark:text-gray-300">{{ t('components.realtime_monitor.real_time_speed_legend') }}</span>
            </div>
            <div class="flex items-center">
              <div class="w-3 h-3 bg-green-500 rounded-full mr-2"></div>
              <span class="text-gray-600 dark:text-gray-300">{{ t('components.realtime_monitor.avg_speed_legend') }}</span>
            </div>
          </div>
        </div>
        
        <div class="relative h-64">
          <canvas ref="chartCanvas" class="w-full h-full"></canvas>
        </div>
      </div>

      <!-- 详细统计 -->
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div class="bg-gray-50 dark:bg-[#141414] rounded-lg p-4">
          <h4 class="text-md font-semibold text-gray-900 dark:text-white mb-3">
            <Clock class="w-4 h-4 inline mr-2" />
            {{ t('components.realtime_monitor.running_stats') }}
          </h4>
          <div class="space-y-2 text-sm">
            <div class="flex justify-between">
              <span class="text-gray-600 dark:text-gray-400">{{ t('components.realtime_monitor.duration') }}:</span>
              <span class="font-medium text-gray-900 dark:text-white">{{ formattedDuration }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600 dark:text-gray-400">{{ t('components.realtime_monitor.bytes_consumed') }}:</span>
              <span class="font-medium text-gray-900 dark:text-white">{{ formattedBytesConsumed }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600 dark:text-gray-400">{{ t('components.realtime_monitor.data_points') }}:</span>
              <span class="font-medium text-gray-900 dark:text-white">{{ realtimeHistory.length }}</span>
            </div>
          </div>
        </div>

        <div class="bg-gray-50 dark:bg-[#141414] rounded-lg p-4">
          <h4 class="text-md font-semibold text-gray-900 dark:text-white mb-3">
            <Target class="w-4 h-4 inline mr-2" />
            {{ t('components.realtime_monitor.performance_metrics') }}
          </h4>
          <div class="space-y-2 text-sm">
            <div class="flex justify-between">
              <span class="text-gray-600 dark:text-gray-400">{{ t('components.realtime_monitor.current_level') }}:</span>
              <span :class="[
                'font-medium px-2 py-1 rounded text-xs',
                getLevelColorClass(currentLevel)
              ]">
                {{ getLocalizedLevelName(currentLevel) }}
              </span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600 dark:text-gray-400">{{ t('components.realtime_monitor.efficiency') }}:</span>
              <span class="font-medium text-gray-900 dark:text-white">
                {{ getEfficiencyPercent() }}%
              </span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600 dark:text-gray-400">{{ t('components.realtime_monitor.status') }}:</span>
              <span class="font-medium text-gray-900 dark:text-white">
                {{ getSpeedStatus() }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import { useBandwidthStore } from '@/stores/bandwidth'
import { BandwidthLevel } from '@/types'
import { useI18n } from '@/composables/useI18n'
import {
  Activity,
  Monitor,
  Zap,
  TrendingUp,
  BarChart3,
  Wifi,
  Clock,
  Target
} from 'lucide-vue-next'
import {
  Chart,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler,
  LineController
} from 'chart.js'

// 注册Chart.js组件
Chart.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler,
  LineController
)

const store = useBandwidthStore()
const { t } = useI18n()
const chartCanvas = ref<HTMLCanvasElement>()
let chart: Chart | null = null

// 从store中获取响应式数据
const {
  isRunning,
  currentLevel,
  formattedCurrentSpeed,
  formattedSpeedMBps,
  formattedPeakSpeed,
  formattedAvgSpeed,
  formattedDuration,
  formattedBytesConsumed,
  activeConnections,
  realtimeHistory,
  levelInfos
} = storeToRefs(store)

// 获取等级信息
const getLevelInfo = (level: BandwidthLevel) => {
  return levelInfos.value[level]
}

// 获取国际化的等级名称
const getLocalizedLevelName = (level: BandwidthLevel): string => {
  const levelKey = level.toLowerCase()
  return t(`levels.${levelKey}`)
}

// 获取等级颜色样式
const getLevelColorClass = (level: BandwidthLevel) => {
  switch (level) {
    case BandwidthLevel.Micro:
      return 'bg-lime-100 text-lime-800'
    case BandwidthLevel.Mini:
      return 'bg-green-100 text-green-800'
    case BandwidthLevel.Low:
      return 'bg-emerald-100 text-emerald-800'
    case BandwidthLevel.Medium:
      return 'bg-yellow-100 text-yellow-800'
    case BandwidthLevel.High:
      return 'bg-orange-100 text-orange-800'
    case BandwidthLevel.Turbo:
      return 'bg-rose-100 text-rose-800'
    case BandwidthLevel.Ultra:
      return 'bg-red-100 text-red-800'
    case BandwidthLevel.Extreme:
      return 'bg-red-200 text-red-900'
    default:
      return 'bg-gray-100 text-gray-800'
  }
}

// 计算效率百分比
const getEfficiencyPercent = (): number => {
  const levelInfo = getLevelInfo(currentLevel.value)
  if (!levelInfo || !store.currentSpeed) return 0
  
  const targetSpeed = levelInfo.speed_mbps
  const actualSpeed = store.currentSpeed
  
  return Math.min(Math.round((actualSpeed / targetSpeed) * 100), 100)
}

// 获取速度状态
const getSpeedStatus = (): string => {
  const speed = store.currentSpeed
  if (speed >= 50) return t('components.realtime_monitor.status_extreme')
  if (speed >= 20) return t('components.realtime_monitor.status_high')
  if (speed >= 5) return t('components.realtime_monitor.status_medium')
  if (speed >= 1) return t('components.realtime_monitor.status_low')
  return t('components.realtime_monitor.status_standby')
}

// 初始化图表
const initChart = () => {
  if (!chartCanvas.value) {
    console.warn('图表canvas元素不存在，无法初始化图表')
    return
  }
  
  // 如果图表已存在，先销毁
  if (chart) {
    chart.destroy()
    chart = null
  }
  
  const ctx = chartCanvas.value.getContext('2d')
  if (!ctx) {
    console.warn('无法获取canvas 2d上下文')
    return
  }
  
  try {
    chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: [],
        datasets: [
          {
            label: '实时速度 (Mbps)',
            data: [],
            borderColor: 'rgb(59, 130, 246)',
            backgroundColor: 'rgba(59, 130, 246, 0.1)',
            tension: 0.1,
            fill: true,
            pointRadius: 2,
            pointHoverRadius: 4,
            borderWidth: 2
          },
          {
            label: '平均速度 (Mbps)',
            data: [],
            borderColor: 'rgb(16, 185, 129)',
            backgroundColor: 'rgba(16, 185, 129, 0.1)',
            tension: 0.1,
            fill: false,
            pointRadius: 2,
            pointHoverRadius: 4,
            borderWidth: 2
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        animation: {
          duration: 0 // 禁用动画以提高性能
        },
        plugins: {
          title: {
            display: false
          },
          legend: {
            position: 'top' as const,
            labels: {
              usePointStyle: true,
              pointStyle: 'circle'
            }
          },
          tooltip: {
            mode: 'index' as const,
            intersect: false,
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            titleColor: 'white',
            bodyColor: 'white',
            borderColor: 'rgba(255, 255, 255, 0.1)',
            borderWidth: 1
          }
        },
        scales: {
          x: {
            display: true,
            title: {
              display: true,
              text: '时间'
            },
            grid: {
              color: 'rgba(0, 0, 0, 0.1)'
            },
            ticks: {
              maxTicksLimit: 10 // 限制x轴标签数量
            }
          },
          y: {
            display: true,
            title: {
              display: true,
              text: '速度 (Mbps)'
            },
            beginAtZero: true,
            grid: {
              color: 'rgba(0, 0, 0, 0.1)'
            }
          }
        },
        interaction: {
          mode: 'nearest' as const,
          axis: 'x',
          intersect: false
        },
        elements: {
          point: {
            radius: 2,
            hoverRadius: 4
          },
          line: {
            borderWidth: 2
          }
        }
      }
    })
    
    console.log('图表初始化成功')
    
    // 如果有历史数据，立即更新图表
    if (store.realtimeHistory.length > 0) {
      nextTick(() => {
        updateChart()
      })
    }
  } catch (error) {
    console.error('图表初始化失败:', error)
  }
}

// 更新图表数据
const updateChart = () => {
  if (!chart) return
  
  const data = store.chartData
  
  // 检查数据有效性
  if (!data || !data.labels || !data.datasets) {
    console.warn('图表数据无效，跳过更新')
    return
  }
  
  // 更新图表数据
  chart.data.labels = [...data.labels]
  chart.data.datasets = data.datasets.map(dataset => ({
    ...dataset,
    data: [...dataset.data]
  }))
  
  // 强制重新渲染
  chart.update('none') // 使用 'none' 模式避免动画干扰
}

// 监听图表数据变化
watch(() => store.chartData, () => {
  if (!chart) return
  
  // 添加防抖处理，避免频繁更新
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }
  debounceTimer = setTimeout(() => {
    updateChart()
  }, 100)
}, { deep: true, immediate: true })

// 监听实时历史数据变化
watch(() => store.realtimeHistory, (newHistory) => {
  if (!chart || !newHistory || newHistory.length === 0) return
  
  // 当有新数据时，确保图表更新
  nextTick(() => {
    updateChart()
  })
}, { deep: true })

// 监听运行状态
watch(() => store.isRunning, async (newVal) => {
  if (newVal) {
    await nextTick()
    if (!chart && chartCanvas.value) {
      initChart()
    }
    // 开始监控时重置图表
    if (chart) {
      chart.data.labels = []
      chart.data.datasets.forEach(dataset => {
        dataset.data = []
      })
      chart.update('none')
    }
  } else {
    // 停止监控时清理图表数据
    if (chart) {
      chart.data.labels = []
      chart.data.datasets.forEach(dataset => {
        dataset.data = []
      })
      chart.update('none')
    }
  }
})

// 添加防抖定时器属性
let debounceTimer: ReturnType<typeof setTimeout> | null = null

onMounted(async () => {
  await nextTick()
  if (store.isRunning && chartCanvas.value) {
    initChart()
  }
})

onUnmounted(() => {
  // 清理防抖定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer)
    debounceTimer = null
  }
  
  if (chart) {
    chart.destroy()
    chart = null
  }
})
</script> 